if
statement in javascript?
if
statement would be using the switch
statement. Although it is less verbose
and is more ordered, it's not
recommended to use it because
it's so difficult to debug
errors. Here's
why.
switch. If we pass true
as a parameter to the switch
statement, it allows us to put a
conditional in each case.
switch
as much as possible. We also must take
into account that the most efficient
way to do this is through an object.
array.sort()
will treat each array entry as a
string and sort it alphabetically.
Also you can provide your
own custom sorting
function.
['é', 'a',
'ú', 'c'], you will obtain a strange result ['c', 'e',
'á', 'ú']. That happens because sort works
only with the English language.
Both methods have their own custom parameters in order to configure it to work adequately.
localeCompare()
Intl.Collator()
undefined
means a variable has not been
declared, or has been declared
but has not yet been assigned
a value
null
is an assignment value that
means "no
value"
undefined
null. It is used by programmers
to indicate that a var
has no value.
undefined
is not valid in JSON while null
is
undefined
typeof is undefined
printUpperCase
is now ready to accept a single node
or an array of nodes as its parameter.
It also avoids the potential TypeError
that would be thrown if no parameter
was passed.
querySelectorAll
method returns an array-like object
called a node list. These data
structures are referred to as
"Array-like", because they
appear as an array, but can not be
used with array methods like map
and forEach. Here's a quick, safe, and
reusable way to convert a node list
into an array of DOM elements:
apply
method is used to pass an array of
arguments to a function with a given this
value.
MDN
states that apply
will take an array-like object, which
is exactly what querySelectorAll
returns. Since we don't need to
specify a value for this
in the context of the function, we
pass in null
or 0. The result is an actual array of
DOM elements which contains all of the
available array methods.
Array.prototype.slice
combined with Function.prototype.call
or Function.prototype.apply
passing the array-like object as the
value of this:
${}
in template strings.
in
operator
and
Object.hasOwnProperty. Every object descended from Object, has both ways available.
hasOwnProperty
will only return true if key is
available on that object directly.
However, the in
operator doesn't discriminate
between properties created on an
object and properties inherited from
the prototype chain.
_err
is a function that immediately
throws an Error. If no value is
passed for one of the parameters,
the default value is going to be
used, _err
will be called and an Error will be
thrown. You can see more examples
for the default parameters feature
on
Mozilla's Developer
Network
console.time(label)
and
console.timeEnd(label)
Note: As Mozilla suggested don't use this for production sites, use it for development purposes only.
=>, which is a 'fat arrow',
as compared to a thin arrow ->. Some programmers might already know
this type of function from different
languages such as Haskell, as
'lambda expressions', or as
'anonymous functions'. It is
called anonymous, as these arrow
functions do not have a descriptive
function name.
function
keyword over and over
again
this
from the surrounding
context
(x,y) => x+y. It is just a way to cope with
forgetting them in different use
cases. But the code above would also
work like this: x => x*x. So far, these are only syntactical
improvements, which lead to fewer LOC
and better readability.
this
this. With arrow functions, you
don't need to worry about .bind(this)
or setting that = this
anymore, as fat arrow functions pick
the context of this
from the lexical surrounding. Have a
look at the next [example]
(https://jsfiddle.net/pklinger/rw94oc11/):
-1
into 0, and 0
evaluates to false
in JavaScript:
x
and y
are in scope of the callback function
when it is called.
bind
method. For example:
require('./something.js')
or node something.js. This is useful if you want to
interact with one of your modules
independently.
~~
operator? It's also often called the
"double bitwise NOT"
operator. You can often use it as a
faster substitute for Math.trunc(). Why is that?
~
first truncates input
to 32 bits, then transforms it into -(input+1). The double bitwise shift therefore
transforms the input into -(-(input + 1)+1)
making it a great tool to round
towards zero. For numeric input, it
therefore mimics Math.trunc(). On failure, 0
is returned, which might come in handy
sometimes instead of Math.trunc(), which returns NaN
on failure.
~~
is probably a better performer,
experienced programmers often stick
with Math.trunc()
instead. To understand why,
here's a clinical view on this
operator.
~~
is probably faster than Math.trunc()
across the board, though you should
test that assumption
on whichever platforms matter to you.
Also, you'd generally have to
perform millions of such operations to
have any visible impact at run
time.
Always code as if the person who ends up maintaining your code is a violent psychopath who knows where you live.
~~
always rounds to zero
~~, forgetting the significance of
"just drop the fractional portion
of this number". This can easily
lead to fencepost errors
(a.k.a. "off-by-one") when
transforming floats to array indices
or related ordinal values, where a
different kind of fractional rounding
may actually be called for. (Lack of
code clarity usually contributes to
this problem.)
Math.round()
instead of ~~, but programmer laziness and the
impact of 10 whole characters saved per
use
on human fingers often triumph over
cold logic, leading to incorrect
results.
Math.xyz()
functions clearly communicate their
effect, reducing the probability of
accidental errors.
~
first does a 32-bit conversion, ~~
results in bogus values around ±2.15
billion. If you don't properly
range-check your input, a user could
trigger unexpected behavior when the
transformed value ends up being a
great distance from the
original:
~~
transforms every non-number into 0:
0
values. This is therefore not
a recommended practice.
~~X == Math.floor(X)
Math.floor()
for some reason. If you can't
write about it accurately, odds are
good you'll eventually misuse
it.
Math.floor()
for positive inputs and Math.ceil()
for negative ones, but that forces you
to stop and think about the values
you're dealing with. This defeats
the purpose of ~~
as a handy no-gotchas shortcut.
0
values
concat:
join
type
of concatenation, the speed of concat
is pretty much the same.
list = []
assigns a reference to a new
array to a variable, while any
other references are
unaffected. which means that
references to the contents of
the previous array are still
kept in memory, leading to
memory leaks.
list.length = 0
deletes everything in the
array, which does hit other
references.
a = [1,2,3]; a2 = a;), and you delete the array's
contents using list.length = 0, both references (a and a2) will now
point to the same empty array. (So
don't use this technique if you
don't want a2 to hold an empty
array!)
+
(plus) operator.
-
(minus) operator which type-converts
the value into number but also negates
it.
==
(or !=) operator performs an automatic type
conversion if needed. The ===
(or !==) operator will not perform any
conversion. It compares the value and
the type, which could be considered
faster (jsPref) than ==.
filter, which will return a new filter
array based in a predicate (function) we pass to it. The predicate will
compare the index of the current
keyword in the original list with its index
in the new list and will push it to
the new array only if the indexes
match.
sort
function which takes a comparison
function as the only argument,
returning a alphabetically sorted
list.
&&) function evaluates to false, the
overall value must be false; and when
the first argument of the OR (||) function evaluates to true, the
overall value must be true.
test
condition and isTrue
and isFalse
function.
&&.
||.
memoize()
in many other situations
arguments
lets you access all of the arguments
passed to the function. arguments
is an array-like object; arguments
can be accessed using array notation,
and it has the length
property, but it doesn't have
many of the built-in methods that
arrays have such as filter
and map
and forEach. Because of this, it is a fairly
common practice to convert arguments
into an array using the
following:
slice
method from the Array
prototype, passing it arguments; the slice
method returns a shallow copy of arguments
as a new array object. A common
shorthand for this is :
slice
from the Array
prototype, it is simply being called
from an empty array literal.
arguments
into any function call will cause the
V8 JavaScript engine used in Chrome
and Node to skip optimization on the
function that does this, which can
result in considerably slower
performance. See this article on
optimization killers. Passing arguments
to any other function is known as leaking arguments.
An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method. ECMAScript
for...of
loop returns an array of [key, value]
for each iteration.
So, if you want to simulate an ordered associative array in a cross-browser environment, you are forced to either use two separate arrays (one for the keys and the other for the values), or build an array of single-property objects, etc.
N-element array [0, 1, ..., N-1]:
Array.apply(null, {length:
N})
returns an N-element array filled with undefined
(i.e. A = [undefined, undefined,
...]).
A.map(Function.call,
Number)
returns an N-element array, whose index I
gets the result of Function.call.call(Number,
undefined, I, A)
Function.call.call(Number,
undefined, I, A)
collapses into Number(I), which is naturally I.
[0, 1, ..., N-1].
A = new Array(N)
returns an array with N
holes
(i.e. A = [,,,...], but A[x] = undefined
for x
in 0...N-1).
F =
(val,index)=>index
is simply function F (val, index) {
return index; }
Array.from(A, F)
returns an N-element array, whose index I
gets the results of F(A[I], I), which is simply I.
[0, 1, ..., N-1].
i, not a copy. So the for loop
increments i
until it gets to 5, then the timeouts
run and use the current value of i
(which is 5).
i. The most common way is creating a
closure by declaring a function and
passing i
as an argument. Here we do this as a
self-calling function.
let. With ES6 the let
keyword is useful since it's
block scoped unlike var
++
and --
operators
++
operator. It's best to explain it
with an example:
a++
statement does this:
a
a
by 1
--
operator is similar, except it
decrements the value.
Object, the keys will always be of the type String. This means that normally we
can't distinguish between strings
and numbers of the same value, i.e. 1
and '1'.
JSON.stringify, keys that are of the type String, will be stored as an escaped string
value, giving us unique keys in our hashTable.
defineProperty
of the Object
prototype like so:
{a: 12}
=== Object.defineProperty(obj,
'a', {value:
12})
for ... of
loops and stringify
will not include the property
in their result, but the
property is still there. Note:
That doesn't mean that
the property is private! It
can still be accessible from
the outside, it just means
that it won't be
printed.
defineProperty
allows us to define dynamic properties, thanks to the second parameter
being a string. For instance,
let's say that I want to create
properties according to some external
configuration:
writable, enumerable
and configurable
properties, but instead:
a.b.c[0].d
(where one of the properties can
resolve to undefined
and throw an error), we can instead
create an alias:
$.extend
or _.merge. Be careful!
sum/length)
prev
array from the bind meaning that any .concat
the first concat call following using
the unapply attack will throw an
error.
= {}
says that the default object to be
destructured for this parameter is {}, in case the caller forgets to pass
the parameter, or passes one of the
wrong type (more on this below).
undefined, so you need to add code that
handles this properly:
= {}, it covers the case of a missing object, for which individual property
defaults won't help at all:
--harmony-destructuring
flag on startup to activate this
feature.
myTeam
gets invoked, JavaScript is passing the reference to
me
object as value, as it is an
object
and invocation itself creates two
independent references to the same
object, (though the name being same
here i.e. me, is misleading and gives us an
impression that it is the single
reference) and hence, the reference
variable themselves are
independent.
3, we are changing this reference
value entirely within the myTeam
function, and it will not have any
impact on the original object outside
this function scope, from where it was
passed and the reference in the
outside scope is going to retain the
original object and hence the output
from #4.
myGroup
invocation, we are passing the object me. But unlike the example 1 scenario,
we are not assigning this me
variable to any new object,
effectively meaning the object
reference value within the myGroup
function scope still is the original
object's reference value and when
we are modifying the property within
this scope, it is effectively
modifying the original object's
property. Hence, you get the output
from #4.
Function.prototype.apply()
allows you to call a function with a
given this
value and an array
of arguments.
numbers
array as the second argument of apply()
results in the function being called
with all values in the array as
parameters.
document.readyState ===
'interactive'
to detect when the DOM is ready.
reduce()
method applies a function against an
accumulator and each value of the
array (from left-to-right) to reduce
it to a single value.
YYYY-MM-DD
or YYYY-MM-DDT00:00:00Z
as parameter of Date
constructor. For example
+
sign also when declaring a Date
object like below
valueOf
method of the Date
object. Then the unary +
operator calls toNumber()
with that returned value. For detailed
explanation please check the following
links
element.addEventListener('type',
obj.method.bind(obj))
element.addEventListener('type',
function (event) {})
element.addEventListener('type',
(event) => {})
new
to allocate new objects in JavaScript.
It's going to blow your mind
unless you read this tip to understand
what's happening behind the
scenes.
new
operator in JavaScript is an operator
that, under reasonable circumstances,
returns a new instance of an object.
Let's say we have a constructor
function:
this
refers to the new object created by new. Otherwise if Thing()
is called without new, no object is created, and this
is going to point to the global
object, which is window. This means that:
one
and two.
myThing
is now undefined, since
nothing is returned in Thing().
new
keyword, you can set properties on it
using the keyword this
(but you probably already knew that).
Returning a primitive value from a
function you called with the new
keyword will not return the value you
specified, but instead will return the this
instance of the function (the one you
put properties on, like this.one = 1;).
object, array, or function
will stomp on the this
instance, and return that
non-primitive instead, effectively
ruining all the hard work you did
assigning everything to this.
split
method
slice, lastIndexOf
methods
'.'
in this case). Returns -1
if the value is not
found.
lastIndexOf
for parameter 'filename'
and '.hiddenfile'
are -1
and 0
respectively.
Zero-fill right shift
operator
(>>>)
will transform -1
to 4294967295
and -2
to 4294967294, here is one trick to insure
the filename unchanged in
those edge cases.
"".
split
slice, lastIndexOf
%
( Modulus ) operator is prettier.The
modulus return division's rest ( 2 % 5 = 1
and 5 % 5 = 0):
<input/>
with the text to be copied to the DOM.
Then, we selected the content and
execute the copy command with
execCommand. execCommand('copy')
will copy the actual selected
content.
copy, cut, paste, and make changes like fonts color,
size, and much more.
,) operator has the lowest
priority of all javascript
operators, so without the
parenthesis the expression
would become: (x = a()), b(), c();.
for
loops we can break
to end iteration early.
.forEach
but then we lack the ability to break. In this situation the closest we
get is continue
functionality through return.
.some
is a method on Array prototype. It
tests whether some element in the
array passes the test implemented by
the provided function. If any value is
returning true, then it stops
executing. Here is a
MDN link
for more details.
.some
we get iteration functionally similar
to .forEach
but with the ability to break
through return
instead.
false
to make it continue
to next item. When you return true, the loop will break
and a.some(..)
will return
true.
.every, which can be used. We have to
return the opposite boolean compared
to .some.
var
is function scope or declared
outside any function,
global.
let
is block scope.
let
will not hoist to the entire
scope of the block they appear
in. By contrast, var
could hoist as below.
let
in the loop can re-binds it to
each iteration of the loop,
making sure to re-assign it
the value from the end of the
previous loop iteration, so it
can be used to avoid issue
with closures.
var
with let
var
with let?
NO,letis the new block scopingvar. That statement emphasizes thatletshould replacevaronly whenvarwas already signaling block scoping stylistically. Otherwise, leavevaralone.letimproves scoping options in JS, not replaces.varis still a useful signal for variables that are used throughout the function.
let
compatibility
let
statement now.
true, like this:
this
parameter value to be passed to target
function while calling the bound
function.
bound
function while invoking the target
function.
this
value and initial arguments.
timerID
variable. Let’s have a look on
implementation-
keepAlive()
function at the end of onOpen()
method of websocket connection and cancelKeepAlive()
function at the end of onClose()
method of websocket connection.
Array.apply
when creating the array.
null
or undefined.
null
since JavaScript treats it as an
object and that’s just weird. With the
introduction of spread operators in
ES6, there is a neater way of passing
empty parameters to a method. As
previously mentioned, arrays are
sparse in nature and so passing empty
values to it is totally okay.
We'll use this to our
advantage.
Set
constructor to generate unique array
values.
console.log? Let me show you an example:
bank_info
isn't returning anything, so
we'll tap it:
false
printed, so there's no client
with >25000, that's why the
function was returning nothing.
n! = n * (n - 1) * ... * 1
is a standard example.
n = 6:
maximum stack size exceeded
error.
select
just a few fields for some
function:
map
a function over the keys that will
return, each time, an object with only
the attribute pointed by the current
key (or an empty object if
there's no such attribute in the
object). Then, we reduce
this collection of single-attribute
objects by merging the objects.
reject
the attributes? Well, the function
changes a bit
NaturalNumbers
are Mappable, we can call map
on them and trust it will return the
right result. Furthermore, with our
third function, we can compose
any number of operations defined in
protocols cleanly:
Mappable, we know map
will work on it. Protocols gives us an
idea of what we can do with an object
and help us abstract common operations
between data types, thus reducing the
overhead of dealing with a hundred
functions.
JS shall have but one Thread (in the browser at least)-- Thus spoke the master programmer.
async
functions, which will be queued as
soon as invoked and executed as soon
as possible (immediately given the
queue is empty).
async
function.
newWorker = new
Worker('my_worker.js');
and offload the processing to
it.
i
is represented internally.
let
scopes the variable to our for
loop and produces a new value each
iteration, thus i
will be bound to different values on
our closures as expected.
map
solves this by applying a function
over every element and then returning
the new array.
map
is .map(current_value, index,
array).
The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
const map = {}), the map inherits properties from
Object by default. It is equivalent to Object.create(Object.prototype).
Object.create(null), we explicitly specify null
as its prototype. So it have
absolutely no properties, not even
constructor, toString, hasOwnProperty,
etc. so you're free to use those
keys in your data structure if you
need to.
Immutability in object means we don’t want our objects to change in any ways once we create them i.e make them read-only type.
preventExtensions()
is a irreversible operation. We can
never add extra properties to the
object again.
seal()
also prevents the modification of
property descriptors.
Object.seal()
plus it makes the properties
non-writable.
strict mode
if you want to throw an error when
trying to modify an immutable
object.
let
and const
keywords. Since the keywords are
block-scoped, the variables declared
these keywords could not be accessed
before the declaration, and then you
will have to witness where variables
will be said to be undefined.
target
refers to the DOM element that
triggers an event. Otherwise, currentTarget
refers to the DOM element that the
event listener is listening on.
void
operator returns an undefined
value from an evaluated expression, or
in other words; the void
operator specifies an expression to be
evaluated without returning a value.
It is commonly used in client-side
JavaScript, where the browser should
not display the value.
Promise
instances accept a method as an
argument called the executor. This
executor takes two methods as
arguments: resolve and reject. Within
the executor, if resolve is called,
the Promise
instance becomes fulfilled. If an
exception is thrown, reject is called
instead, and the Promise
instance becomes rejected.
if
statement. It consists of three
operands; a question mark, a
condition, and an expression to
execute if the condition is true,
followed by a colon and another
expression to execute if it’s
false.